package com.kaigejava.juc.queue;

import com.google.common.collect.Maps;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 模拟缓存有效期
 */
@Data
public class MyCache  implements Delayed {

    //缓存时间
    private Long time;
    private String key;
    private Object value;
    private Map<String,Object> map;

    public MyCache( Long time, String key,Object value){
        this.time = time;
        this.key = key ;
        this.value = value;
        map = Maps.newHashMap();
        map.put(key,value);
        this.time = TimeUnit.NANOSECONDS.convert(time, TimeUnit.MILLISECONDS) + System.nanoTime();
        this.map = map;
    }


    /**
     * 重写过期时间
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        Long l= unit.convert(time - System.nanoTime(), unit);
        return l;
    }


    /**
     * 比较大小
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        MyCache cache = (MyCache)o;
        int i = time > cache.time?1:(time < cache.time ? -1 : 0);;
       return i;

    }
}
